package com.web.app.ctrl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.web.app.config.UserDataListener;
import com.web.app.dao.ClassInfoMapper;
import com.web.app.dao.StudentInfoMapper;
import com.web.app.dao.UserMapper;
import com.web.app.pojo.ExcelUserData;
import com.web.app.pojo.StudentInfo;
import com.web.app.pojo.User;
import com.web.app.service.IUserService;
import com.web.app.util.MyFileUtil;
import com.web.app.util.ResultUtil;
import com.web.app.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 林
 * @since 2022-09-21
 */
@RestController
@CrossOrigin
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Value("${muban}")
    private String filepath;


    @RequestMapping("/getImage")
    public void getImage(String url,HttpServletResponse response){
        MyFileUtil.fileDownload(url,response);
    }

    @RequestMapping("/vertoken")
    public ResultUtil vertoken(HttpServletRequest request){
        ResultUtil ok = ResultUtil.ok();
        String token = request.getHeader("Authorization");
        try {
            String id = TokenUtil.getItem(token, "id");
            User user = userMapper.selectById(id);
            //处理一下，把密码清空
            ok.setData(user);
            return ok;
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    @RequestMapping("/login")
    public ResultUtil login(User user){
        ResultUtil resultUtil = new ResultUtil();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getUserName());
        queryWrapper.eq("password",user.getPassword());
        List<User> users = userMapper.selectList(queryWrapper);
        if(users.size() == 1){
            User user1 = users.get(0);
            Map<String,String> userData = new HashMap<>();
            userData.put("username",user1.getUserName());
            userData.put("id",user1.getId()+"");
            String token = TokenUtil.getToken(7, userData);
            resultUtil.setMsg(token);
            resultUtil.setData(user1);
            resultUtil.setCode(0);
            return resultUtil;
        }else {
            return ResultUtil.error("登录失败！");
        }
    }

    @RequestMapping("/getStudentByClassId")
    public ResultUtil getStudentByClassId(int id) {
        ResultUtil resultUtil = ResultUtil.ok();
        try {
            //根据班级id获取学生信息
            List<User> users = userMapper.selectMyList(id);
            resultUtil.setData(users);
        }catch (Exception e){
            return ResultUtil.error(e.getMessage());
        }
        return resultUtil;
    }

    @RequestMapping("/addStudnet")
    public ResultUtil addStudnet(User user) {
        System.err.println(user);
        user.setPassword("123456");
        ResultUtil resultUtil = ResultUtil.ok();
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name",user.getUserName());
            List<User> users = userMapper.selectList(queryWrapper);
            if(users != null && users.size() > 0){
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setRelationClassId(user.getStatus());
                studentInfo.setUserId(users.get(0).getId());

                //重复验证
                QueryWrapper<StudentInfo> sq = new QueryWrapper<>();
                sq.eq("relation_class_id",studentInfo.getRelationClassId());
                sq.eq("user_id",studentInfo.getUserId());
                List<StudentInfo> studentInfos = studentInfoMapper.selectList(sq);
                if(studentInfos != null && studentInfos.size() > 0){
                    return ResultUtil.error("该班级已添加过该学生！");
                }

                studentInfoMapper.insert(studentInfo);
                return resultUtil;
            }

            //根据班级id获取学生信息
            int i = userMapper.insert(user);
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setRelationClassId(user.getStatus());
            studentInfo.setUserId(user.getId());
            studentInfoMapper.insert(studentInfo);
        }catch (Exception e){
            return ResultUtil.error(e.getMessage());
        }
        return resultUtil;
    }

    @RequestMapping("/updatePwd")
    public ResultUtil updatePwd(User user,String oldpwd,String newpwd) {
        System.err.println(user);
        ResultUtil resultUtil = ResultUtil.ok("修改成功");
        try {
            User sqluser = userMapper.selectById(user.getId());
            if(sqluser.getPassword().equals(oldpwd)){
                user.setPassword(newpwd);
                userMapper.updateById(user);
            }else{
                return ResultUtil.error("旧密码有误，修改失败");
            }
        }catch (Exception e){
            return ResultUtil.error(e.getMessage());
        }
        return resultUtil;
    }

    @RequestMapping("/editStudnet")
    public ResultUtil editStudnet(User user) {
        //拒绝修改账号
        user.setUserName(null);
        System.err.println(user);
        ResultUtil resultUtil = ResultUtil.ok();
        try {
            //根据班级id获取学生信息
            int i = userMapper.updateById(user);
        }catch (Exception e){
            return ResultUtil.error(e.getMessage());
        }
        return resultUtil;
    }

    @RequestMapping("/delStu")
    public ResultUtil delStu(int id) {
        ResultUtil resultUtil = ResultUtil.ok();
        try {
            //根据班级id获取学生信息
            int i = userMapper.deleteById(id);
        }catch (Exception e){
            return ResultUtil.error(e.getMessage());
        }
        return resultUtil;
    }

    @RequestMapping("/studentAddM")
    public ResultUtil studentAddM(MultipartFile file) {
        ResultUtil resultUtil = ResultUtil.ok();
        try {
            EasyExcel.read(
                    file.getInputStream(),
                    ExcelUserData.class,
                    new UserDataListener(userMapper,classInfoMapper,studentInfoMapper)).sheet().doRead();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    @RequestMapping("/updateUserAvatar")
    public String updateUserAvatar(MultipartFile file,int id) {
        try {
            String fileName = MyFileUtil.fileUpload("r2003v", file);
            User user = new User();
            user.setId(id);
            user.setUserAvatar(fileName);
            userMapper.updateById(user);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @RequestMapping("/down")
    public void down(HttpServletResponse response) {
        System.out.println(filepath);
        MyFileUtil.fileDownload(filepath,response);
    }

    @RequestMapping("/downfile")
    public void down(HttpServletResponse response,String url) {
        MyFileUtil.fileDownload(url,response);
    }
}

